package com.autonomous_printer.controller;

import com.autonomous_printer.pojo.File;
import com.autonomous_printer.pojo.Manager;
import com.autonomous_printer.pojo.Order;
import com.autonomous_printer.service.ManageService;
import com.autonomous_printer.util.PrinterStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class ManageController {

    @Autowired
    ManageService manageService;

    @Autowired
    PrinterStatus printerStatus;

    @PostMapping("/adminLogin")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password, HttpSession session) {
        Manager manager = new Manager(username, password);
        if (manageService.queryManager(manager)) {
            session.setAttribute("admin", manager);
            return "redirect:/uploadFiles";
        }

        return "manage/login";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        Object admin = session.getAttribute("admin");
        if (admin != null) {
            session.removeAttribute("admin");
        }
        return "index";
    }

    @GetMapping("/uploadFiles")
    public String message(Model model, HttpSession session) {
        Object admin = session.getAttribute("admin");
        if (admin == null) {
            return "manage/login";
        }
        List<File> files = manageService.queryFileAll();
        List<Order> orders = manageService.queryOrderAll();
        double ink = printerStatus.getInk();
        int page = printerStatus.getPage();

        model.addAttribute("files", files);
        model.addAttribute("orders", orders);
        model.addAttribute("ink", ink);
        model.addAttribute("page", page);
        return "manage/message";
    }

    @GetMapping("/addPageOrInk")
    public String addPageOrInk(@RequestParam("page") int page, @RequestParam("ink") double ink, HttpSession session) {
        Object admin = session.getAttribute("admin");
        if (admin == null) {
            return "manage/login";
        }
        if (page > 1000 || page < 0) {//纸张数量校验
            return "manage/message";
        }
        if (ink < 0 || ink > 100) {//墨水含量校验
            return "manage/message";
        }
        printerStatus.setPage(page);
        printerStatus.setInk(ink);
        return "redirect:/uploadFiles";
    }

}
